<template>
  <div class="container">
    <div class="app-containering" v-show="!departmentStore.loading">
      <div class="left">
        <el-input
          v-model="queryParams.keyword"
          placeholder="输入员工姓名全员搜索"
          prefix-icon="el-icon-search"
          size="small"
          style="margin-bottom: 10px"
          type="text"
          @input="changeValue"
        />
        <!-- 树形组件 -->
        <el-scrollbar height="80vh">
          <el-table
            v-loading="departmentStore.loading"
            :data="departmentStore.departmentList"
            :tree-props="{ children: 'childs', hasChildren: 'hasChildren' }"
            border
            default-expand-all
            element-loading-text="加载中..."
            row-key="selfid"
          >
            <OrganizationNameColumn
              hoverable="true"
              selectable="true"
              @select="selectNode"
            />
          </el-table>
        </el-scrollbar>
      </div>
      <div class="right">
        <el-row class="opeate-tools" justify="end" type="flex">
          <el-select
            v-model="selectstatus"
            clearable
            placeholder="员工状态筛选"
            style="width: 200px; margin-right: 30px"
            @change="selectionstatus"
          >
            <el-option
              v-for="item in optionsStatus"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
          <el-button type="primary" @click="handldAdd">添加员工</el-button>
          <el-button type="primary" @click="handleImportClick">更新员工信息</el-button>
          <el-button type="primary" @click="handleExportClick">导出</el-button>
        </el-row>
        <!-- 表格组件 -->
        <el-table :data="newEmployeeData" style="width: 100%" height="80vh">
          <el-table-column align="center" label="头像" prop="staffPhoto">
            <template v-slot="{ row }">
              <el-avatar v-if="row.staffPhoto" :size="30" :src="row.staffPhoto" />
              <span v-else class="username">{{ row.username.charAt(0) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="手机号" prop="mobile" sortable />
          <el-table-column label="工号" prop="workNumber" sortable />
          <el-table-column label="聘用形式" prop="typeOfEmployment">
            <template v-slot="{ row }">
              <span v-if="row.typeOfEmployment == 1">全职</span>
              <span v-else-if="row.typeOfEmployment == 2">兼职</span>
              <span v-else>无</span>
            </template>
          </el-table-column>
          <el-table-column label="办公地点" prop="locattionOfWork">
            <template v-slot="{ row }">
              <span v-if="row.locattionOfWork == 1">办公室</span>
              <span v-else-if="row.locattionOfWork == 2">门店</span>
              <span v-else>无</span>
            </template>
          </el-table-column>
          <el-table-column label="入职时间" prop="timeOfEntry" sortable>
            <template v-slot="{ row }">
              {{
                row.timeOfEntry ? new Date(row.timeOfEntry).toLocaleDateString() : "暂无"
              }}
            </template>
          </el-table-column>
          <el-table-column label="状态" prop="status" width="80px">
            <template v-slot="{ row }">
              <span v-if="row.status == '已离职'" style="color: #ff0034">
                {{ row.status }}
              </span>
              <span v-else-if="row.status == '已激活'" style="color: #56bc5b">
                {{ row.status }}
              </span>
              <span v-else="row.status == '未激活'" style="color: #c0c4cc">
                {{ row.status }}
              </span>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="230px">
            <template v-slot="{ row }">
              <div>
                <el-button
                  :disabled="
                    row.status == '未激活' || row.status == ' ' || row.status == '已离职'
                  "
                  size="small"
                  type="primary"
                  @click="editEmployee(row)"
                  >编辑
                </el-button>
                <el-button
                  :disabled="
                    row.status == '未激活' || row.status == ' ' || row.status == '已离职'
                  "
                  size="small"
                  type="danger"
                  @click="handleDel(row)"
                  >离职
                </el-button>
                <el-button
                  :disabled="row.status == '已激活' || row.status == '已离职'"
                  size="small"
                  type="primary"
                  @click="activation(row.userid)"
                  >同步激活
                </el-button>
              </div>
              <div style="margin-top: 5px">
                <el-button size="small" type="primary" @click="RenewClick(row.userid)"
                  >续约记录
                </el-button>
                <el-button
                  :disabled="row.status != '已离职'"
                  size="small"
                  type="primary"
                  @click="ReOnboarding(row)"
                  >重新入职
                </el-button>
              </div>
            </template>
          </el-table-column>

          <template #empty>
            <el-empty :image-size="100" description="暂无员工数据" />
          </template>
        </el-table>
      </div>
    </div>
  </div>
  <import-excel-dialog v-model="isImportDialogShow" title="导入员工" />

  <!-- 续约记录 -->
  <el-dialog
    v-model="XuyueDialogVisible"
    :close-on-click-modal="false"
    title="变动记录"
    width="400"
  >
    <el-table :data="XuyuegridData" style="width: 100%" height="250">
      <el-table-column property="work_number" label="入职工号" width="120" />
      <el-table-column property="entry_date" label="入职日期" />
      <el-table-column property="leave_date" label="离职日期" />
    </el-table>
  </el-dialog>

  <!-- 员工记录 -->
  <el-dialog v-model="employeeManageVisible" title="员工续约" width="500">
    <employeeRenew @clickchild="clickEven"></employeeRenew>
  </el-dialog>
</template>

<script lang="ts" setup>
import { onMounted, reactive, ref } from "vue";
import { ElMessage } from "element-plus";
import { deleteUserInfo, getUserInfo, getuserStatu } from "@/api/employee";
import { useDepartmentStore } from "@/stores/department";
import { useRouter } from "vue-router";
import { useEmployeeStore } from "@/stores/employee";
import {
  EmployeeResponse,
  translateIsCleaner,
  translateLocationOfWork,
  translateTypeOfEmployment,
} from "@/api/types/employee";
import { utils, writeFile } from "xlsx";
import ImportExcelDialog from "@/components/dialog/ImportExcelDialog.vue"; // 引入 Pinia store
import { getDepartmentList } from "@/api/department";

import { getrenewalInfo } from "@/api/employee";

const departmentStore = useDepartmentStore();

const router = useRouter(); // 引入路由

// 员工添加输入框可编辑
const addyuangong = ref(true);

const employeeStore = useEmployeeStore(); // 创建 store 实例
const employeeManageVisible = ref(false);

const clickEven = (val: any) => {
  employeeManageVisible.value = false;
};
let deleteval: {
  dept_id?: any;
} = {};

// 定义转换函数生成部门选项
function transformDataForCascader(data: any) {
  return data.map((item: any) => ({
    value: `${item.selfid}`,
    label: item.dept_name,
    children:
      item.childs && item.childs.length ? transformDataForCascader(item.childs) : null,
  }));
}

//离职部门选择
const selectedOptions = ref(""); // 存储用户选择的结果
const cascaderOptions = ref([]); //遍历数据

// 定义改变事件处理器
const handleCascaderChange = (value: any) => {
  if (value.length > 0) {
    selectedOptions.value = value[value.length - 1];
    deleteval.dept_id = selectedOptions.value;
  }
};

//续约list
const XuyueDialogVisible = ref(false);
const XuyuegridData = ref([]);

const deleteDialogVisible = ref(<Boolean>false);
//部门数据
const employeeData = ref(<Array<unknown> | any>[]);
const total = ref(<number>0);
const defaultExpandedKeys = ref([] as number[]);

//员工数据
const newEmployeeData = ref(<any>[]);

// 存储查询参数，记录节点
const queryParams: {
  id: any;
  page?: any;
  pagesize?: any;
  keyword?: any;
} = reactive({
  id: null,
  page: 1, //当前页
  pagesize: 10,
  keyword: "",
});
//删除人员id
const delId = ref(<number>0);

//状态数据
const selectstatus = ref("");

//状态选项
const optionsStatus = [
  {
    value: "已激活",
    label: "已激活",
  },
  {
    value: "未激活",
    label: "未激活",
  },
  {
    value: "已离职",
    label: "已离职",
  },
];

//状态监听进行筛选
const selectionstatus = (val: any) => {
  if (val) {
    if (employeeData.value.length > 0) {
      if (val == "已激活") {
        newEmployeeData.value = employeeData.value.filter((item: any) => {
          return item.status == "已激活";
        });
      } else if (val == "未激活") {
        newEmployeeData.value = employeeData.value.filter((item: any) => {
          return item.status == "未激活";
        });
      } else if (val == "已离职") {
        newEmployeeData.value = employeeData.value.filter((item: any) => {
          return item.status == "已离职";
        });
      }
    }
  } else {
    newEmployeeData.value = employeeData.value;
  }
};

onMounted(async () => {
  try {
    await departmentStore.fetchDepartmentList();
    // await getUserData();
  } catch (error) {
    console.error("获取部门信息失败:", error);
  }
});

//获取表格数据
const getUserData = async () => {
  const res = await getUserInfo(queryParams.id);

  newEmployeeData.value = [];

  employeeData.value = [];
  res.data.forEach((item: { userid: string | null }) => {
    if (item.userid != null && item.userid != " ") {
      employeeData.value.push(item);
    }
  });
  newEmployeeData.value = employeeData.value;
};

//搜索员工
const changeValue = () => {};

//切换节点
const selectNode = async (node: any) => {
  // console.log(node);

  selectstatus.value = "";
  employeeStore.setEmployeeDeptname(node.dept_name);
  currentDepartmentName.value = node.dept_name;
  queryParams.id = node.selfid; //重新记录参数
  queryParams.page = 1; //设置第一页

  getUserData();
};



//激活员工
const activation = async (userid: any) => {
  const resq = await getuserStatu(userid);

  const res = await getUserInfo(queryParams.id);

  newEmployeeData.value = [];

  employeeData.value = [];
  res.data.forEach((item: { userid: string | null; }) => {
    if (item.userid != null && item.userid != " ") {
      employeeData.value.push(item);
    }
  });
  newEmployeeData.value = employeeData.value;
};



//兼职续约
const editEmployeepart = (row: any) => {
  console.log(row);
  employeeManageVisible.value = true;
  employeeStore.setEmployeeInfo(row); // 将员工信息存储到 Pinia store
};

// 续约记录
const RenewClick = async (userid: any) => {
  try {
    const res = await getrenewalInfo(userid);
    if (res.code == "200") {
      XuyueDialogVisible.value = true;
      XuyuegridData.value = res.data;
    } else {
      ElMessage.error("查询失败");
    }
  } catch (error) {
    console.error(error);
  }
};

const ReOnboarding = (row: any) => {
  employeeStore.setEmployeeInfo(row); // 将员工信息存储到 Pinia store
  router.push("/employeeManage/ReOnboarding");
};

// 编辑员工
const editEmployee = (row: any) => {
  employeeStore.settype("Edit");
  employeeStore.setEmployeeInfo(row); // 将员工信息存储到 Pinia store
  router.push("/employeeManage/detail"); // 跳转到详情页
};


//离职按钮
const handleDel = async (row: any) => {
  console.log(row);
  employeeStore.settype("del");
  employeeStore.setEmployeeInfo(row); // 将员工信息存储到 Pinia store
  router.push({
    path: "/employeeManage/detail",
  });
};

//新增员工
const handldAdd = () => {
  employeeStore.setEmployeeInfo({});
  employeeStore.settype("add");
  router.push({
    path: "/employeeManage/detail",
  });

  // router.push(`/employeeManage/detail/${queryParams.id}`);
};




const currentDepartmentName = ref<string>();

function handleExportClick() {
  if (employeeData.value.length > 0) {
    const processedData: {
      ID?: string;
      用户ID?: string;
      工号?: string;
      手机号?: string;
      用户名?: string;
      部门?: string;
      邮箱?: string;
      工作地点?: "办公室" | "门店";
      状态?: "未激活" | "已激活";
      入职时间?: string;
      聘用形式?: "全职" | "兼职";
      基本工资?: number;
      转正日期?: string;
      带教老师?: string;
      是否清洁工?: "是" | "不是";
      身份证号?: string;
      银行账号?: string;
      银行名字?: string;
      职位?: string;
    }[] = newEmployeeData.value.map((employee: EmployeeResponse) => ({
      ID: employee.id,
      用户ID: employee.userid,
      工号: employee.workNumber?.toString(),
      手机号: employee.mobile?.toString(),
      用户名: employee.username,
      部门: currentDepartmentName.value,
      邮箱: employee.email,
      工作地点:
        employee.locattionOfWork !== undefined
          ? translateLocationOfWork(employee.locattionOfWork)
          : undefined,
      状态: employee.status,
      入职时间: employee.timeOfEntry,
      聘用形式:
        employee.typeOfEmployment !== undefined
          ? translateTypeOfEmployment(employee.typeOfEmployment)
          : undefined,
      基本工资: employee.basic_salary,
      转正日期: employee.timeOfEntry,
      带教老师: employee.teacher_name,
      是否清洁工:
        employee.is_cleaner !== undefined
          ? translateIsCleaner(employee.is_cleaner)
          : undefined,
      身份证号: employee.id_card,
      银行账号: employee.bank_account,
      银行名字: employee.bank_name,
      职位: employee.position,
      离职日期: employee.leave_date,
    }));
    const workBook = utils.book_new();
    const workSheet = utils.json_to_sheet(processedData);
    utils.book_append_sheet(workBook, workSheet);
    writeFile(workBook, "output.xlsx");
  } else {
    ElMessage.error("没有数据可以导出");
  }
}

const isImportDialogShow = ref(false);

function handleImportClick() {
  isImportDialogShow.value = true;
}
</script>

<style lang="scss" scoped>
// .container{
//    background: #fff;
//   height: 100%;
//    width: 100%;
// }

.app-containering {
  background: #fff;
  display: flex;

  .left {
    width: 260px;
    padding: 20px;
    border-right: 1px solid #eaeef4;
  }

  .right {
    width: 100%;
    padding: 20px;

    .opeate-tools {
      margin: 10px;
    }

    .username {
      height: 30px;
      width: 30px;
      line-height: 30px;
      text-align: center;
      border-radius: 50%;
      color: #fff;
      background: #04c9be;
      font-size: 12px;
      display: inline-block;
    }
  }
}
</style>
